package com.vancouver.knows.ui.activity.version;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.VersionInfo;
import com.vancouver.knows.util.AppUtils;

/**
 *  "success":"Y",
 * "data":{
 *"app_ver":"1.0.0",
 *"update_message":"1.新增城惠模块.\n2.修订异常退出的bug.",
 *"download_url":"market://detail?id=com.vancouver.knows"
 */
public class UpdateDialog extends Dialog {	
	private Context mContext;
    private Button mConfirm;
    private Button mCancel;
    private String url;
    private TextView tittle;
    private TextView content;
    private VersionInfo info;

    public UpdateDialog(Context context) {
        super(context, R.style.UpdateDialog);
        mContext = context;
        BusinessModule bModule = ((MainApplication) mContext.getApplicationContext()).getBusinessModule();
        info = bModule.getCacheManager().getVersionInfoCache();
        if (info != null) {
            url = info.getDownLoadUrl();
         }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_dialog);
        //设置为点击对话框之外的区域对话框不消失
        this.setCanceledOnTouchOutside(false);

        mConfirm = (Button) findViewById(R.id.dialog_confirm);
        mCancel = (Button) findViewById(R.id.dialog_cancel);
        tittle = (TextView)findViewById(R.id.tittle);
        content = (TextView)findViewById(R.id.content);
        //如果是强制更新， 按钮变成退出
        if(isForceUpdate()) {
            mCancel.setText(mContext.getString(R.string.exit));
        }
    	tittle.setText("Version: " + AppUtils.getAppVer(mContext));

    	String contentText = paramData(info);
    	content.setText(contentText);

        //设置事件
        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtils.hasInstallGGP(mContext)) {
                    update();
                } else {
                    Toast.makeText(mContext, mContext.getString(R.string.no_googleplay), Toast.LENGTH_LONG).show();
                    //如果没有安装googleplay服务，又是大版本更新，则退出应用
                    if (isForceUpdate()){
                        System.exit(0);
                    }
                }
            }
        });     
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isForceUpdate() ) {
                    //是大版本，点击cancel，退出应用
                    System.exit(0);
                }else {
                    UpdateDialog.this.dismiss();
                }
            }

        });
    }

    private boolean isForceUpdate() {
        boolean result = false;
        int versionFlag = 2; //强制更新版本判断位(前两位)
        int[] newVersionArray = AppUtils.getArray(info.getAppVer());
        int[] currentVersionArray = AppUtils.getArray(AppUtils.getAppVer(mContext));
        for(int i = 0 ; i < versionFlag; i++) {
            if(currentVersionArray[i] < newVersionArray[i]) {
                //说明是大版本
                result = true;
                break;
            }
        }
        return result;
    }

    private String paramData(VersionInfo info) {
        String versionMsg = info.getUpdateMsg();
        return versionMsg;
    }
    
    OnCancelListener mListener;
    @Override
    public void setOnCancelListener(final OnCancelListener listener) {
    	mListener = listener;
    }
    
    private void update() {
    		updateFromGP(url);
    }
    
    private void updateFromGP(String mUrl){
    	Uri uri = Uri.parse(mUrl);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClassName("com.android.vending", "com.android.vending.AssetBrowserActivity");
		mContext.startActivity(intent);
    }    

    @SuppressLint("NewApi")
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){  
			mCancel.callOnClick();
		}  
		return true;
    }
}
